package com.madao.im.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * spring jackson
 *
 * @author chengjunchao
 * @version 1.0.0
 * @date 2021/12/6 18:29
 */
@Component
public class JacksonUtil {
    private static ObjectMapper objectMapper;

    private static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    /**
     * 先在application.properties配置好jackson的，然后将jacksonObjectMapper注入到自定义的变量objectMapper
     *
     * @param jacksonObjectMapper
     */
    @Autowired
    public void setObjectMapper(ObjectMapper jacksonObjectMapper) {
        JacksonUtil.objectMapper = jacksonObjectMapper;
    }

    public static String toJson(Object data) {
        try {
            String result = objectMapper.writeValueAsString(data);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toBean(String jsonData, Class<T> beanType) {
        try {
            T result = objectMapper.readValue(jsonData, beanType);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toBean(String jsonData, TypeReference<T> typeReference) {
        try {
            T result = objectMapper.readValue(jsonData, typeReference);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
